package com.xinzhitong.www.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.xinzhitong.www.exception.*;
import com.xinzhitong.www.exception.comment.EmptyCommentException;
import com.xinzhitong.www.exception.company.CompanyIdInvalidException;
import com.xinzhitong.www.exception.picture.PictureEmptyException;
import com.xinzhitong.www.exception.post.PostIsEmptyException;
import com.xinzhitong.www.mapper.CompanyMapper;
import com.xinzhitong.www.mapper.PostMapper;
import com.xinzhitong.www.pojo.Company;
import com.xinzhitong.www.pojo.User;
import com.xinzhitong.www.service.CompanyService;
import com.xinzhitong.www.utils.FileHelper;
import com.xinzhitong.www.utils.MyPageInfo;
import com.xinzhitong.www.utils.PropertiesHelper;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;

/**
 * 公司服务实现类
 *
 * @author 徐鑫
 */
@Service
@Transactional
public class CompanyServiceImpl implements CompanyService {

    @Resource
    CompanyMapper companyMapper;

    @Resource
    PostMapper postMapper;

    @Override
    public Company getCompanyInfo(Integer id) throws CompanyException {
        Company company = companyMapper.selectCompanyById(id);
        if (company == null)
            throw new CompanyIdInvalidException();
        company.setLogo(FileHelper.fileURL + company.getLogo());
        return company;
    }

    @Override
    public String[] getCompanyPictures(Integer id) throws CompanyPictureException {
        String[] pictures = companyMapper.selectPictureByCompanyId(id);
        for (int i = 0; i < pictures.length; i++)
            pictures[i] = FileHelper.fileURL + pictures[i];

        if (pictures.length == 0)
            throw new PictureEmptyException();
        return pictures;
    }

    @Override
    public MyPageInfo getPostsOfCompanyOf(Integer id, Integer pageNo, Integer pageSize) throws PostException {
        PageHelper.startPage(pageNo, pageSize);
        List<Map<String, Object>> posts = postMapper.selectPostsByCompanyId(id);
        if (posts.isEmpty())
            throw new PostIsEmptyException();
        //补全url
        for (Map<String, Object> post : posts)
            post.put("picture", FileHelper.fileURL + post.get("picture"));
        PageInfo<Map<String, Object>> pageInfo = new PageInfo<>(posts);
        return new MyPageInfo(pageInfo);
    }

    @Override
    public void commentCompanyOf(Integer companyId, String text) throws CompanyIdInvalidException {
        Subject subject = SecurityUtils.getSubject();
        User user = (User) subject.getPrincipal();
        if (companyMapper.selectCompanyById(companyId) == null)
            throw new CompanyIdInvalidException();
        if (companyMapper.insertUserCommentCompany(user.getUsername(), companyId, text) == 0)
            throw new BusyException();
    }

    @Override
    public MyPageInfo getCommentsOf(Integer companyId, Integer pageNo, Integer pageSize) throws CommentException {
        PageHelper.startPage(pageNo, pageSize);
        List<Map<String, Object>> res = companyMapper.selectUserCommentCompanyByCompanyId(companyId);
        if (res.size() == 0)
            throw new EmptyCommentException();
        for (Map<String, Object> one : res)
            one.put("head", FileHelper.fileURL + one.get("head"));
        PageInfo<Map<String, Object>> pageInfo = new PageInfo<>(res);
        return new MyPageInfo(pageInfo);
    }

    @Override
    public Set<String> getCompanyType() {
        return getEnum("nature");
    }

    public List<Map<String, Object>> getCompanyView(Integer pageNo, Integer pageSize) {
        Integer[] ids;
        Properties properties = new Properties();
        // 使用InPutStream流读取properties文件
        try {
            BufferedReader bufferedReader =
                    new BufferedReader(
                            new InputStreamReader(
                                    Objects.requireNonNull(PropertiesHelper.class
                                            .getClassLoader()
                                            .getResourceAsStream("ourCompanies.properties"))));
            properties.load(bufferedReader);
            String indexString = (String) properties.get("companiesId");
            String[] indexesString = indexString.split(",");
            ids = new Integer[indexesString.length];
            for (int i = 0; i < indexesString.length; i++)
                ids[i] = Integer.valueOf(indexesString[i]);
        } catch (IOException e) {
            e.printStackTrace();
            throw new BusyException();
        }
        List<Map<String, Object>> res = new ArrayList<>();
        int sta = 0, end = ids.length;
        if (pageSize != 0) {
            sta = (pageNo - 1) * pageSize;
            end = pageNo * pageSize;
        }

        for (int i = sta; i < end; i++) {
            Map<String, Object> tmp = new HashMap<>();
            Company company = companyMapper.selectCompanyById(ids[i]);
            if (company == null)
                continue;
            tmp.put("logo", FileHelper.fileURL + company.getLogo());
            tmp.put("id", company.getId());
            tmp.put("name", company.getName());
            res.add(tmp);
        }
        return res;
    }

    @Override
    public Set<String> getIndustry() {
        return getEnum("industry");
    }

    /**
     * 获取枚举类列表
     *
     * @param field 枚举字段
     * @return 枚举类值集合
     */
    private Set<String> getEnum(String field) {
        List<String> industryOfCompany = Arrays.asList(companyMapper.selectEnumOf(field).split("[,']"));
        Set<String> industryTypeSet = new HashSet<>(industryOfCompany);
        industryTypeSet.remove("");
        industryTypeSet.remove("enum(");
        industryTypeSet.remove(")");
        return industryTypeSet;
    }

}
